<?php

namespace App\Http\Controllers;

use App\Models\Member;
use App\Models\Red;
use Illuminate\Http\Request;
use Kuyuan\Phpwidget\File;

class PosterController extends Controller
{
    /**
     * 获取红包海报所需数据
     */
    public function show($_id)
    {
        $Red = Red::where("id",$_id)->select("title","member_id")->first();
        $Member = Member::where("id",$Red->member_id)->select("nickname","avatar")->first();
        $_data = array(
            "title" => $Red->title,
            "nickname" => $Member->nickname,
            "header" => $this->wxHeaderToLocation($Member->avatar,$Red->member_id),
            "qrcode" => route('app',['share_id'=>$this->getShareId($_id)])
        );
        return response(["data"=>$_data]);
    }

    /**
     * 将微信头像拉取到本地
     * @param $_url
     * @param $_member_id
     * @return mixed
     */
    private function wxHeaderToLocation($_url,$_member_id)
    {
        $_dir = "avatar/";
        $_dir = storage_path('app/public/'.$_dir);
        if(!is_dir($_dir)) {
            mkdir($_dir,0777,true);
        }
        $_filename = $_dir.$_member_id.'.jpg';
        if(!is_file($_filename)) {
            $hander = curl_init();
            curl_setopt($hander,CURLOPT_URL,$_url);
            curl_setopt($hander, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($hander,CURLOPT_HEADER,0);
            curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
            curl_setopt($hander,CURLOPT_TIMEOUT,60);
            $_data = curl_exec($hander);
            curl_close($hander);
            file_put_contents($_filename,$_data);
        }
        return cool_media("avatar/".$_member_id.".jpg");
    }
}
